package speelotheek.views;

import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.UIManager;
import javax.swing.LayoutStyle.ComponentPlacement;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;
import java.util.Calendar;
import java.util.ArrayList;

import javax.swing.BoxLayout;
import javax.swing.JButton;

import speelotheek.configs.Config;
import speelotheek.models.Kind;
import speelotheek.models.Lid;
import javax.swing.JRadioButton;
import javax.swing.ImageIcon;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AddCustomer extends JDialog {

	/**
	 * 
	 */	
	private static final long serialVersionUID = -1941500718355988139L;
	
	private static Config config;
	
	private JTextField nrField;
	private JTextField naamField;
	private JTextField adresField;
	private JTextField pcField;
	private JTextField wpField;
	private JTextField emailField;
	private JTextField telField;
	private JLabel lblAddStatus;
	private JLabel lblAddChildStatus;
	
	private ArrayList<String> customerErrors;
	private ArrayList<Kind> kindArray;
	private Lid nieuwLid;
	private Kind nieuwKind;
	
	private JTextField childNameField;
	private JTextField childBirthField;
	private JRadioButton rdbChildM;
	private JRadioButton rdbChildV;
	private JButton btnSave;
	private JButton btnSaveChild;
	private JLabel lblChildAmount;

	/**
	 * Create the dialog.
	 */
	public AddCustomer() {
		config = new Config();
		
		setBounds(100, 100, 640, 500);
		setTitle("Lid - Toevoegen");
		setLocationRelativeTo(null);
		setModal(true);
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Lid Toevoegen:", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		getContentPane().add(panel);
		
		JLabel lblNaam = new JLabel("Naam:");
		
		nrField = new JTextField();
		nrField.setEnabled(false);
		nrField.setColumns(10);
		
		JLabel lblAdres = new JLabel("Adres:");
		
		naamField = new JTextField();
		naamField.setColumns(10);
		
		JLabel lblPostcode = new JLabel("Postcode:");
		
		adresField = new JTextField();
		adresField.setColumns(10);
		
		JLabel lblWoonplaats = new JLabel("Woonplaats:");
		
		pcField = new JTextField();
		pcField.setColumns(10);
		
		JLabel lblEmail = new JLabel("Email:");
		
		wpField = new JTextField();
		wpField.setColumns(10);
		
		JLabel lblTelefoon = new JLabel("Telefoon:");
		
		emailField = new JTextField();
		emailField.setColumns(10);
		
		JLabel lblNummer = new JLabel("Nummer:");
		
		telField = new JTextField();
		telField.setColumns(10);
		
		lblAddStatus = new JLabel("");
		
		btnSave = new JButton("Toevoegen");
		btnSave.setIcon(new ImageIcon(AddCustomer.class.getResource("/speelotheek/resources/add_16.png")));
		btnSave.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent arg0) {
				try {
					nieuwLid = _addCustomer();
					_changeFields("customer", false);
					lblAddStatus.setText("<html><body><font color='green'><strong>Nieuw Lid Toevoegen Geslaagd</strong></font></body></html>");
				}
				catch(Exception ex) {
					_displayErrors();
					lblAddStatus.setText("<html><body><font color='red'><strong>Nieuw Lid Toevoegen Mislukt</strong></font></body></html>");
				}
				
				if(nieuwLid != null) {
					_changeFields("child", true);
				}
            }			
		});
		
		GroupLayout gl_panel = new GroupLayout(panel);
		gl_panel.setHorizontalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addGap(52)
					.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
						.addComponent(lblTelefoon)
						.addComponent(lblNummer)
						.addComponent(lblNaam)
						.addComponent(lblAdres)
						.addComponent(lblPostcode)
						.addComponent(lblWoonplaats)
						.addComponent(lblEmail))
					.addGap(18)
					.addGroup(gl_panel.createParallelGroup(Alignment.LEADING, false)
						.addComponent(nrField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(adresField)
						.addComponent(naamField, GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
						.addComponent(pcField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(wpField)
						.addComponent(emailField)
						.addComponent(telField, GroupLayout.PREFERRED_SIZE, 121, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED, 71, Short.MAX_VALUE)
					.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
						.addComponent(btnSave)
						.addComponent(lblAddStatus, GroupLayout.PREFERRED_SIZE, 237, GroupLayout.PREFERRED_SIZE))
					.addContainerGap())
		);
		gl_panel.setVerticalGroup(
			gl_panel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel.createSequentialGroup()
					.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel.createSequentialGroup()
							.addContainerGap()
							.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
								.addComponent(nrField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblNummer))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
								.addComponent(naamField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblNaam))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
								.addComponent(adresField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblAdres))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
								.addComponent(pcField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblPostcode))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
								.addComponent(wpField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblWoonplaats))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
								.addComponent(emailField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblEmail)))
						.addComponent(lblAddStatus))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblTelefoon)
						.addComponent(telField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnSave))
					.addContainerGap())
		);
		panel.setLayout(gl_panel);
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(null, "Kinderen Toevoegen:", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		getContentPane().add(panel_1);
		
		lblAddChildStatus = new JLabel("");
		
		JLabel lblAantalKinderen = new JLabel("Aantal Kinderen:");
		
		lblChildAmount = new JLabel("0");
		
		JLabel lblNaam_1 = new JLabel("Naam:");
		
		childNameField = new JTextField();
		childNameField.setEnabled(false);
		childNameField.setColumns(10);
		
		JLabel lblGeslacht = new JLabel("Geslacht:");
		
		rdbChildM = new JRadioButton("Jongen");
		rdbChildM.setEnabled(false);
		
		rdbChildV = new JRadioButton("Meisje");
		rdbChildV.setEnabled(false);
		
		ButtonGroup bGroup = new ButtonGroup();
		bGroup.add(rdbChildM);
		bGroup.add(rdbChildV);
		
		childBirthField = new JTextField();
		childBirthField.setEnabled(false);
		childBirthField.setColumns(10);
		
		JLabel lblJjjjmmdd = new JLabel("JJJJ-MM-DD");
		
		JLabel lblGeboortedatum = new JLabel("Geboortedatum:");
		
		kindArray = new ArrayList<Kind>();
		
		btnSaveChild = new JButton("Toevoegen");		
		btnSaveChild.setIcon(new ImageIcon(AddCustomer.class.getResource("/speelotheek/resources/add_16.png")));
		btnSaveChild.setEnabled(false);
		btnSaveChild.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent arg0) {
				try {
					nieuwKind = _addChild();
					lblAddChildStatus.setText("<html><body><font color='green'><strong>"+nieuwKind.getNaam()+" Toegevoegd</strong></font></body></html>");
				}
				catch(Exception ex) {
					_displayErrors();
					lblAddChildStatus.setText("<html><body><font color='red'><strong>Nieuw Kind Toevoegen Mislukt</strong></font></body></html>");
				}
				
				if(nieuwKind != null) {
					kindArray.add(nieuwKind);
					lblChildAmount.setText(Integer.toString(kindArray.size()));
					childNameField.setText("");
					childBirthField.setText("");
					rdbChildM.setSelected(false);
					rdbChildV.setSelected(false);
				}
            }			
		});
		
		JLabel lblToegevoegd = new JLabel("toegevoegd");
		
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addGap(29)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING)
						.addComponent(lblNaam_1)
						.addComponent(lblAantalKinderen)
						.addComponent(lblGeslacht)
						.addComponent(lblGeboortedatum))
					.addGap(18)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel_1.createSequentialGroup()
							.addComponent(lblChildAmount)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(lblToegevoegd)
							.addPreferredGap(ComponentPlacement.RELATED, 208, Short.MAX_VALUE)
							.addComponent(lblAddChildStatus, GroupLayout.PREFERRED_SIZE, 193, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_panel_1.createSequentialGroup()
							.addComponent(rdbChildM)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(rdbChildV))
						.addGroup(gl_panel_1.createSequentialGroup()
							.addComponent(childBirthField, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE)
							.addGap(18)
							.addComponent(lblJjjjmmdd)
							.addPreferredGap(ComponentPlacement.RELATED, 195, Short.MAX_VALUE)
							.addComponent(btnSaveChild))
						.addComponent(childNameField, GroupLayout.PREFERRED_SIZE, 162, GroupLayout.PREFERRED_SIZE))
					.addContainerGap())
		);
		gl_panel_1.setVerticalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_panel_1.createSequentialGroup()
							.addContainerGap()
							.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblAantalKinderen)
								.addComponent(lblChildAmount)
								.addComponent(lblToegevoegd))
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblNaam_1)
								.addComponent(childNameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblGeslacht)
								.addComponent(rdbChildM)
								.addComponent(rdbChildV)))
						.addComponent(lblAddChildStatus))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblGeboortedatum)
						.addComponent(childBirthField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(lblJjjjmmdd)
						.addComponent(btnSaveChild))
					.addContainerGap(23, Short.MAX_VALUE))
		);
		panel_1.setLayout(gl_panel_1);
		
		JPanel panel_2 = new JPanel();
		getContentPane().add(panel_2);
		
		JButton btnCancelAll = new JButton("Annuleren");
		btnCancelAll.setIcon(new ImageIcon(AddCustomer.class.getResource("/speelotheek/resources/cross_48.png")));
		btnCancelAll.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg1) {
				if(nieuwLid != null) {
					String msg = "Alle ingevulde gegevens zullen verloren gaan\n\nWeet u zeker dat u wilt Annuleren?\n";
					int confirmCancel = JOptionPane.showConfirmDialog(null, msg, "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
				    
					switch(confirmCancel) {
						case JOptionPane.YES_OPTION:													
							break;
						case JOptionPane.NO_OPTION:
							return;
					}
				}
				dispose();
			}
		});
		
		JButton btnSaveAll = new JButton("Opslaan");
		btnSaveAll.setIcon(new ImageIcon(AddCustomer.class.getResource("/speelotheek/resources/tick_48.png")));
		btnSaveAll.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg2) {
				if(nieuwLid == null) {
					String msg = "Je hebt nog geen lid aangemaakt.\n";
					JOptionPane.showMessageDialog(null, msg, "Error", JOptionPane.ERROR_MESSAGE);
					return;
				} 
				if(kindArray.isEmpty()) {
					String msg = "Er zijn geen kinderen toegevoegd.\n\nWeet u zeker dat u dit lid wilt opslaan zonder kinderen?\n";
					int confirmSave = JOptionPane.showConfirmDialog(null, msg, "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
				    
					switch(confirmSave) {
						case JOptionPane.YES_OPTION:													
							break;
						case JOptionPane.NO_OPTION:
							return;
					}
				}				
				try {
					nieuwLid.addCustomer();
					
					int customerId = nieuwLid.getLatestId();					
					for(Kind child : kindArray) {
						child.saveChild(customerId);
					}
				} 
				catch (Exception ex) {
					String msg = "Database Error\n\n Neem contact op met de beheerder als die probleem zich blijft voordoen.";
					JOptionPane.showMessageDialog(null, msg, "Error", JOptionPane.ERROR_MESSAGE);
					System.out.println(ex);
					return;
				}
				
				dispose();
			}
		});
		
		panel_2.add(btnSaveAll);
		
		panel_2.add(btnCancelAll);
	}
	
	private Lid _addCustomer() throws Exception
	{		
		// Alle text in de textfields ophalen
		String naam = naamField.getText();
		String adres = adresField.getText();
		String postcode = pcField.getText();
		String woonplaats = wpField.getText();
		String email = emailField.getText();
		String telefoon = telField.getText();
		
		Calendar startlidmaatschap = Calendar.getInstance();
		Calendar eindlidmaatschap = Calendar.getInstance();
		eindlidmaatschap.add(Calendar.YEAR, config.MEMBERSHIP_DURATION);
		
		customerErrors = new ArrayList<String>();
		
		if(naam.isEmpty()) {
			customerErrors.add("U heeft geen naam ingevuld");
		}
		if(adres.isEmpty()) {
			customerErrors.add("U heeft geen adres ingevuld");
		}
		if(postcode.isEmpty()) {
			customerErrors.add("U heeft geen postcode ingevuld");
		}
		if(woonplaats.isEmpty()) {
			customerErrors.add("U heeft geen woonplaats ingevuld");
		}
		if(email.isEmpty()) {
			customerErrors.add("U heeft geen email ingevuld");
		}
		if(telefoon.isEmpty()) {
			customerErrors.add("U heeft geen telefoon nummer ingevuld");
		}		
		if(isValidEmail(email) == false) {
			customerErrors.add("U heeft geen geldig email adres ingevuld");
		}
		
		telefoon = telefoon.replaceAll("[^0-9]", "");
		if(telefoon.length() != 10) {
			customerErrors.add("U heeft geen geldig telefoon nummer ingevuld");
		}
		
		if(customerErrors.isEmpty() != true) {
			throw new Exception("Errors on inputfields");
		}
		
		Lid lid = new Lid();
		lid.setNaam(naam);
		lid.setAdres(adres);
		lid.setPostcode(postcode);
		lid.setWoonplaats(woonplaats);
		lid.setEmail(email);
		lid.setTelefoon(telefoon);
		lid.setStartlidmaatschap(new java.sql.Date(startlidmaatschap.getTimeInMillis()));
		lid.setEindlidmaatschap(new java.sql.Date(eindlidmaatschap.getTimeInMillis()));			
		return lid;
	}
	
	private Kind _addChild() throws Exception
	{		
		// Alle text in de textfields ophalen
		String naam = childNameField.getText();
		String geboortedatum = childBirthField.getText();
		String geslacht = "";
		
		if(rdbChildM.isSelected()) {
			geslacht = "M";
		}
		if(rdbChildV.isSelected()) {
			geslacht = "V";
		}		
		
		customerErrors = new ArrayList<String>();
		
		if(naam.isEmpty()) {
			customerErrors.add("U heeft geen naam ingevuld");
		}
		if(geslacht.isEmpty()) {
			customerErrors.add("U heeft geen geslacht aangeklikt");
		}
		if(geboortedatum.isEmpty()) {
			customerErrors.add("U heeft geen geboortedatum ingevuld");
		}
		
		if(customerErrors.isEmpty() != true) {
			throw new Exception("Errors on inputfields");
		}
		
		Kind kind = new Kind();
		kind.setNaam(naam);
		kind.setGeboortedatum(Date.valueOf(geboortedatum));
		kind.setGeslacht(geslacht);
		return kind;
	}
	
	private void _changeFields(String type, boolean en) 
	{
		if(type == "customer") {
			naamField.setEnabled(en);
	        adresField.setEnabled(en);
	        pcField.setEnabled(en);
	        wpField.setEnabled(en);
	        emailField.setEnabled(en);
	        telField.setEnabled(en);
	        btnSave.setEnabled(en);
		}
		if(type == "child") {
			childNameField.setEnabled(en);
			childBirthField.setEnabled(en);
			rdbChildM.setEnabled(en);
			rdbChildV.setEnabled(en);
			btnSaveChild.setEnabled(en);
		}
	}
	
	private void _displayErrors()
	{
		String msg = "Er "+((customerErrors.size() > 1) ? "zijn fouten" : "is een fout")+" opgetreden:\n\n";
		for(String error : customerErrors) {
			msg += "- "+error+"\n";
		}
		JOptionPane.showMessageDialog(null, msg, "error", JOptionPane.ERROR_MESSAGE);
	}
	
	private boolean isValidEmail(String email)
	{
		String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		Pattern pattern = Pattern.compile(EMAIL_PATTERN);
		Matcher matches = pattern.matcher(email);
		return matches.matches();
	}
}
